package mju.cxf.controller.user;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import mju.cxf.constant.MessageConstant;
import mju.cxf.context.BaseContext;
import mju.cxf.dto.CommentDTO;
import mju.cxf.dto.CommentsDTO;
import mju.cxf.entity.Comments;
import mju.cxf.entity.Order;
import mju.cxf.result.Result;
import mju.cxf.service.CommentsService;
import mju.cxf.service.OrderService;
import mju.cxf.service.UserService;
import mju.cxf.service.impl.PhotoServiceImpl;
import mju.cxf.vo.CommentVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Description;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 评论表 前端控制器
 * </p>
 *
 * @author 乐昌新
 * @since 2024-10-28
 */
@RestController
@RequestMapping("/user/api/comments")
@Api(tags = {"用户评论操作"})
@Description("")
public class ICommentsController {
    @Autowired
    private CommentsService commentsService;

    @PostMapping("/count")
    @ApiOperation(value = "评价总数", notes = "用户查看评价总数和有图片评价总数")
    public Result<HashMap<String, Long>> commentCount(@RequestParam int goodsId) {
        LambdaQueryWrapper<Comments> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Comments::getProductId, goodsId).eq(Comments::getStatus, 1);
        final long allCount = commentsService.count(lqw);
        HashMap<String, Long> counts = new HashMap<>();
        counts.put("allCount", allCount);
        lqw.isNotNull(Comments::getPicture);
        final long hasPicCount = commentsService.count(lqw);
        counts.put("hasPicCount", hasPicCount);
        return Result.success(counts);
    }

    @Autowired
    private UserService userService;

    /**
     * 查看全部评价
     *
     * @param goodsId  商品id
     * @param page     当前
     * @param size     大小
     * @param showType 评价类型
     * @return 商品评价列表
     */
    @PostMapping("/list")
    @ApiOperation(value = "所有评价查询", notes = "用户点进商品查查看评价信息")
    public Result<HashMap<String, Object>> commentList(@RequestParam("goodsId") int goodsId,
                                                       @RequestParam("page") int page,
                                                       @RequestParam("size") int size,
                                                       @RequestParam("showType") int showType) {
        LambdaQueryWrapper<Comments> commentsLqw = new LambdaQueryWrapper<>();
        commentsLqw.eq(Comments::getProductId, goodsId).eq(Comments::getStatus, 1);
        commentsLqw.orderByDesc(Comments::getCommentTime);
        if (showType == 1) {
            commentsLqw.isNotNull(Comments::getPicture);
        }
        final Page<Comments> commentPage = commentsService.page(new Page<>(page, size), commentsLqw);
        final List<CommentVO> commentVOS = commentPage.getRecords().stream().map(comment -> CommentVO.builder()
                .comment(comment)
                .user(userService.getById(comment.getUserId()))
                .build()).collect(Collectors.toList());
        HashMap<String, Object> commentMap = new HashMap<>();
        commentMap.put("commentVOS", commentVOS);
        commentMap.put("page", commentPage.getPages());
        commentMap.put("current", commentPage.getCurrent());
        commentMap.put("total", commentPage.getTotal());
        return Result.success(commentMap);
    }

    @Autowired
    private PhotoServiceImpl photoService;
    @Autowired
    private OrderService orderService;

    @PostMapping("/addComment")
    @ApiOperation(value = "用户评价添加", notes = "用户订单完成后评价")
    @Transactional(rollbackFor = Exception.class)
    public Result<String> commentAdd(@RequestBody CommentDTO commentDTO) {
        Comments comment = new Comments();
        comment.setProductId(commentDTO.getValueId());
        comment.setCommentTime(LocalDateTime.now());
        comment.setContent(commentDTO.getContent());
        if (commentDTO.getTypeId() == 1) {
            comment.setPicture(commentDTO.getImageUrl());
        }
        comment.setStatus(0); //默认未审核
        comment.setUserId(BaseContext.getCurrentId());
        if (commentsService.save(comment)) {
            LambdaUpdateWrapper<Order> luw=new LambdaUpdateWrapper<>();
            luw.eq(Order::getId,commentDTO.getOrderId()).set(Order::getStatus,6);
            orderService.update(luw);
            photoService.saveImages(commentDTO.getImageUrl());
            return Result.success(MessageConstant.SUCCESS_MESSAGE);
        }
        return Result.error(MessageConstant.FAILURE_MESSAGE);
    }

}
